package com.myproject.myblogserver.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.myproject.myblogserver.filter.JwtAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity(jsr250Enabled = true) // 启用JSR-250注解支持
public class SecurityConfig {

    private final JwtAuthenticationFilter jwtAuthenticationFilter;

    // 定义公开路径（无需认证）
    public static final String[] PUBLIC_PATHS = {
            // 用户相关
            "/user/**",
            "/user/login",
            "/user/register",
            "/user/refresh-token",
            "/user/getUserInfo/**",
            "/userFollow/**",
            "/userMessage/**",

            // 博客内容
            "/blog/**", // 注意：这会覆盖更具体的/blog路径
            "/blog/get/**",
            "/blog/getPreview/**",
            "/blog/getSearch",

            // 评论系统
            "/blogComment/**",
            "/commentLike/**",
            "/commentReply/**",
            "/commentReplyLike/**",

            // 标签分类
            "/blogTag/**",
            "/tag/**",

            // 收藏与订阅
            "/favoriteFolder/**",
            "/folderBlog/**",
            "/folderSubscription/**",

            // 互动功能
            "/blogLike/**",
            "/viewHistory/**",

            // 验证码服务
            "/verificationCode/**",
            "/verificationCode/send",

            // 静态资源
            "/files/**" // 允许访问 /files 目录下的静态资源
    };

    public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter) {
        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // 禁用 CSRF（因为我们使用的是无状态的 JWT）
        http.csrf(csrf -> csrf.disable());

        // 设置会话管理为无状态（不使用 Session）
        http.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

        // 配置请求的授权规则
        http.authorizeHttpRequests(requests -> requests
                .requestMatchers("**") // 使用公开路径数组
                .permitAll() // 允许公开访问这些接口
                .anyRequest().authenticated()); // 其他所有请求都需要认证

        // 注册 JWT 认证过滤器
        http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }
}